


# 构建观点排序矩阵
class SortedViews(object):
    def __init__(self, symbols_list):
        self.sorted_view_list = []
        self.num_assets = len(symbols_list)
        self.symbols_list = symbols_list

    #
    def AddView(self, symbol1, symbol2, premium, confidence=1):
        if not isinstance(symbol1, list):
            symbol1 = [symbol1]
        if not isinstance(symbol2, list):
            symbol2 = [symbol2]
        self.sorted_view_list.append({"symbol": symbol1, "greaterThan": symbol2, "expectedPremium": premium, "confidence": confidence})

    # Satchell && Scowcroft 方法
    def GetResult_SS(self):
        view_Q = []
        view_weight_P = []
        view_confidence = []
        for view in self.sorted_view_list:
            view_weight_row = [0 for i in range(self.num_assets)]
            symbols = view["symbol"]
            benchmarks = view["greaterThan"]
            premium = view["expectedPremium"]
            confidence = view["confidence"]
            #
            symbol_weights = 1 / len(symbols)
            benchmark_weights = -1 / len(benchmarks)

            for symbol in symbols:
                symbol_index = self.symbols_list.index(symbol)
                view_weight_row[symbol_index] = symbol_weights

            for benchmark in benchmarks:
                if benchmark == None:
                    continue
                benchmark_index = self.symbols_list.index(benchmark)
                view_weight_row[benchmark_index] = benchmark_weights

            view_Q.append(premium)
            view_weight_P.append(view_weight_row)
            view_confidence.append(confidence)

        return view_weight_P, view_Q, view_confidence


def Process_Sorted_Views(symbols_list, sorted_view_list):
    #
    sorted_views = SortedViews(symbols_list=symbols_list)

    for view in sorted_view_list:
        symbol1 = view.get("symbol")
        symbol2 = view.get("greaterThan")
        premium = view["expectedPremium"]
        confidence = view["confidence"]
        #
        if not premium:
            premium = 0.01
        if not confidence:
            confidence = 1
        if symbol2 == "":
            symbol2 = None
        #
        sorted_views.AddView(symbol1, symbol2, premium, confidence)

    view_weight_P, view_Q, view_confidence = sorted_views.GetResult_SS()
    return view_weight_P, view_Q, view_confidence
